package com.ctrip.corp.obt.shard.sql.mybatis.typehandler;

import com.ctrip.corp.obt.generic.utils.NumberUtils;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * @author x.shen
 * @desc 类型转换器，实现jdbcType=char转Java=Integer
 * @since 2023/10/30
 */
@MappedJdbcTypes({JdbcType.VARCHAR, JdbcType.CHAR})
public class CharToIntTypeHandler extends BaseTypeHandler<Integer> {
    /**
     * 插入时设置参数类型
     * @param ps
     * @param i
     * @param parameter
     * @param jdbcType
     * @throws SQLException
     */
    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, Integer parameter, JdbcType jdbcType)
            throws SQLException {
        ps.setString(i, parameter.toString());
    }

    /**
     * 获取时转换回的自定义类型，根据列名获取
     * @param rs
     * @param columnName
     * @return
     * @throws SQLException
     */
    @Override
    public Integer getNullableResult(ResultSet rs, String columnName) throws SQLException {
        String value = rs.getString(columnName);
        return convertToInt(value);
    }

    /**
     * 根据索引位置获取
     * @param rs
     * @param columnIndex
     * @return
     * @throws SQLException
     */
    @Override
    public Integer getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        String value = rs.getString(columnIndex);
        return convertToInt(value);
    }

    /**
     * 根据存储过程获取
     * @param cs
     * @param columnIndex
     * @return
     * @throws SQLException
     */
    @Override
    public Integer getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        String value = cs.getString(columnIndex);
        return convertToInt(value);
    }

    private Integer convertToInt(String value) {
        if (NumberUtils.isNumber(value)) {
            return Integer.parseInt(value);
        }
        return null;
    }
}
